<?php

namespace App\Http\Controllers\Api;

use App\Jobs\System\ChatExpandTypeCheckJob;
use App\Models\WxChat;
use App\Models\WxNotice;
use App\Models\User\WxUser;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\UserUtils;
use Illuminate\Http\Request;


class MessagesController extends BaseController
{

    /**
     * 消息页数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMessages(Request $request)
    {
        $uid = $request->uid;

        // 获取所有相关通知
        $notices = WxNotice::where('user_id', $uid)
            ->where('is_read', 0)
            ->whereIn('notice_type', [100, 0, 1, 7, 8, 101, 2, 3, 5, 102, 4, 6])
            ->orderByRaw('created_at DESC')
            ->get(['created_at', 'title', 'notice_type']);

        // 初始化计数和内容
        $noticeSystemCount = 0;
        $noticeSystemText = '还没有新通知';
        $noticeSystemDate = '';

        $noticeLikeCollectCount = 0;
        $noticeLikeCollectText = '还没有新的赞和收藏';
        $noticeLikeCollectDate = '';

        $noticeCommentCount = 0;
        $noticeCommentText = '还没有新的评论和@';
        $noticeCommentDate = '';

        // 处理通知
        foreach ($notices as $notice) {
            if (in_array($notice->notice_type, [100, 0, 1, 7, 8])) {
                $noticeSystemCount++;
                if ($noticeSystemCount == 1) {
                    $noticeSystemText = $notice->title ?? '';
                    $noticeSystemDate = format_datetime($notice->created_at);
                }
            } elseif (in_array($notice->notice_type, [101, 2, 3, 5])) {
                $noticeLikeCollectCount++;
                if ($noticeLikeCollectCount == 1) {
                    $noticeLikeCollectText = $notice->title;
                    $noticeLikeCollectDate = format_datetime($notice->created_at);
                }
            } elseif (in_array($notice->notice_type, [102, 4, 6])) {
                $noticeCommentCount++;
                if ($noticeCommentCount == 1) {
                    $noticeCommentText = $notice->title;
                    $noticeCommentDate = format_datetime($notice->created_at);
                }
            }
        }

        // 获取圈子未读数
        $noticeCircleCount = UserUtils::user_circle_unread_count($uid);
        $noticeCircleText = '没有新的'.env('circle_call', '圈子').'动态';
        if ($noticeCircleCount > 0) {
            $noticeCircleText = '有'.$noticeCircleCount.'条笔记新发布';
        }

        // 准备返回数据
        $list = [
            ['noticeSystemText' => $noticeSystemText, 'noticeSystemCount' => $noticeSystemCount, 'noticeSystemDate' => $noticeSystemDate],
            ['noticeLikeCollectText' => $noticeLikeCollectText, 'noticeLikeCollectCount' => $noticeLikeCollectCount, 'noticeLikeCollectDate' => $noticeLikeCollectDate],
            ['noticeCommentText' => $noticeCommentText, 'noticeCommentCount' => $noticeCommentCount, 'noticeCommentDate' => $noticeCommentDate],
            ['noticeCircleText' => $noticeCircleText, 'noticeCircleCount' => $noticeCircleCount, 'noticeCircleDate' => '']
        ];

        $data = [
            'common' => [
                'isFollow' => (WxUser::where('id', $uid)->value('weixin_mp_openid') ? true : false),
                'client_id' => GatewayUtils::uid2client_id($uid)
            ],
            'list' => $list
        ];

        return $this->success($data);
    }


    /**
     * 通知详情页数据
     * @param Request $request
     * 系统通知：0，1, 7, 8
     * 赞和收藏通知：2，3，5
     * 评论和充电通知：4，6
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDetailsMessages(Request $request)
    {
        $uid = $request->uid;
        $type = $request->type;
        $limit = $request->limit;
        if(_empty_($limit)){
            $limit = 10;
        }else{
            $limit = _between_($limit, 1, 100);
        }
        if ($type == 0) {
            $list = WxNotice::where('user_id', $uid)
                ->whereIn('notice_type', [100,0, 1, 7, 8])
                ->orderByRaw('created_at DESC')
                ->paginate($limit);
        } else if ($type == 1) {
            $list = WxNotice::where('user_id', $uid)
                ->whereIn('notice_type', [101,2, 3, 5])
                ->orderByRaw('created_at DESC')
                ->paginate($limit);
        } else if ($type == 2) {
            $list = WxNotice::where('user_id', $uid)
                ->whereIn('notice_type', [102,4, 6])
                ->orderByRaw('created_at DESC')
                ->paginate($limit);
        }

        $list->map(function ($v)use($type) {
            $v->icon = Settings::get('app_notice_type_icon_'.$v->icon_type, '');
            if(_empty_($v->icon) && $v->icon_type != 1000){
                $v->icon = Settings::get('app_notice_type_icon_1000', '');
            }
            return $v;
        });

        return $this->success($list);
    }


    /**
     * 已读对应类通知
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function readMessages(Request $request)
    {

        $uid = $request->uid;
        $type = $request->type;
        if ($type == 0) {
            $notice = WxNotice::where('user_id', $uid)
                ->whereIn('notice_type', [100, 0, 1, 7, 8])
                ->update(['is_read' => 1]);
            return $this->success($notice);
        } else if ($type == 1) {
            $notice = WxNotice::where('user_id', $uid)
                ->whereIn('notice_type', [101, 2, 3, 5])
                ->update(['is_read' => 1]);
            return $this->success($notice);
        } else if ($type == 2) {
            $notice = WxNotice::where('user_id', $uid)
                ->whereIn('notice_type', [102, 4, 6])
                ->update(['is_read' => 1]);
            return $this->success($notice);
        }
    }

    /**
     * 查询用户聊天记录列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserChatList(Request $request)
    {
        $uid = $request->uid;
        if($uid && $uid > 0){
            $data = WxChat::where([['user_id','=', $uid],['chat_state','=', 0]])
                ->orWhere([['object_id','=', $uid],['chat_state','=', 0]])->orderBy('id', 'desc')->get();

            //  二维数组去重
            $res = array();

            $data->map(function ($chat) use (&$res, $uid){
                if($chat['object_id'] == $uid){
                    $relative_user_id = $chat['user_id'];
                }else{
                    $relative_user_id = $chat['object_id'];
                }
                if(!isset($res[$relative_user_id])){
                    if($chat['chat_audio_url'] && $chat['chat_audio_length'] > 0){
                        $chat_content = '语音消息';
                    }else if($chat['chat_image']){
                        $chat_content = '图片消息';
                    }else if(_array_key($chat, 'refer_id', 0) > 0){
                        $chat_content = '转发笔记';
                        if($chat->expand_type != 1 || $chat->expand_id != $chat->refer_id){
                            ChatExpandTypeCheckJob::dispatch();
                        }
                    }else if(_array_key($chat, 'contact_apply_id', 0) > 0){
                        $chat_content = '联系信息申请';
                        if($chat->expand_type != 2 || $chat->expand_id != $chat->contact_apply_id){
                            ChatExpandTypeCheckJob::dispatch();
                        }
                    }else if(_array_key($chat, 'adoption_apply_id', 0) > 0){
                        $chat_content = '领养申请';
                        if($chat->expand_type != 3 || $chat->expand_id != $chat->adoption_apply_id){
                            ChatExpandTypeCheckJob::dispatch();
                        }
                    }else{
                        if($chat['expand_type'] > 0){
                            if($chat['expand_type'] == 1){
                                $chat_content = '转发笔记';
                                $chat['refer_id'] = $chat['expand_id'];
                            }else if($chat['expand_type'] == 2){
                                $chat_content = '联系信息申请';
                                $chat['contact_apply_id'] = $chat['expand_id'];
                            }else if($chat['expand_type'] == 3){
                                $chat_content = '领养申请';
                                $chat['adoption_apply_id'] = $chat['expand_id'];
                            }else if($chat['expand_type'] == 4){
                                $chat_content = '商品卡片';
                                $chat['shop_good_id'] = $chat['expand_id'];
                            }else if($chat['expand_type'] == 5){
                                $chat_content = '闲置商品';
                                $chat['used_good_id'] = $chat['expand_id'];
                            }else if($chat['expand_type'] == 7){
                                $chat_content = '组局活动';
                                $chat['bureau_id'] = $chat['expand_id'];
                            }else if($chat['expand_type'] == 8){
                                $chat_content = '选票活动';
                                $chat['voter_id'] = $chat['expand_id'];
                            }else if($chat['expand_type'] == 101){
                                $chat_content = '笔记审核推送';
                            }else if($chat['expand_type'] == 102){
                                $chat_content = '评论审核推送';
                            }else if($chat['expand_type'] == 103){
                                $chat_content = '组局审核推送';
                            }else if($chat['expand_type'] == 104){
                                $chat_content = '选票审核推送';
                            }else if($chat['expand_type'] == 105){
                                $chat_content = '选手审核推送';
                            }else if($chat['expand_type'] == 106){
                                $chat_content = '闲置审核推送';
                            }else if($chat['expand_type'] == 107){
                                $chat_content = env('circle_call', '圈子').'审核推送';
                            }else if($chat['expand_type'] == 108){
                                $chat_content = '学生认证审核推送';
                            }else if($chat['expand_type'] == 109){
                                $chat_content = '身份认证审核推送';
                            }else if($chat['expand_type'] == 110){
                                $chat_content = '俱乐部审核推送';
                            }else{
                                return $this->fail(200006, [], '数据库expand_type不合法');
                            }
                        }else {
                            $chat_content = $chat['chat_content'];
                        }
                    }
                    $assistant_user = (int)Settings::get('app_notice_assistant_user', 0);
                    if(_empty_($assistant_user) || $assistant_user < 0){
                        $chat_content = (UserUtils::is_user_online($relative_user_id) ? '<span style="color: #36d9a0;">[在线]</span> ' : '[离线] ') . $chat_content;
                    }else{
                        if($relative_user_id == $assistant_user){

                        }else{
                            $chat_content = (UserUtils::is_user_online($relative_user_id) ? '<span style="color: #36d9a0;">[在线]</span> ' : '[离线] ') . $chat_content;
                        }
                    }

                    $obj = [
                        'user' => WxUser::where('id', $relative_user_id)->first(FieldUtils::userInfoColums()),
                        'datetime' => format_datetime($chat['created_at']),
                        'chat_content' => _mini_emoji($chat_content, true),
                        'read_count' => ($chat['is_read'] == 0 && $chat['object_id'] == $uid) ? 1 : 0,
                    ];
                    $res[$relative_user_id] = $obj;
                }else{
                    if($chat['is_read'] == 0 && $chat['object_id'] == $uid){
                        $res[$relative_user_id]['read_count'] += 1;
                    }
                }
            });

            return $this->success(array_values($res));
        }else{
            return $this->success([]);
        }
    }


    /**
     * 查询用户是否有未读信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSysMessageCount(Request $request)
    {
        $count = 0;
        $uid = $request->uid;
        if ($uid) {
            $noticeCount = WxNotice::where([['user_id','=', $uid], ['is_read','=', 0]])->count();

            $chatCount = WxChat::where([['object_id','=', $uid],['is_read','=', 0],['chat_state', '=', 0]])->count();
            $circleCount = UserUtils::user_circle_unread_count($uid);
            $count = $noticeCount + $chatCount + $circleCount;
        }
        return $this->success($count);
    }


}
